package com.example.demo.controller;

import cn.idev.excel.FastExcel;
import com.example.demo.config.ExcelListener;
import com.example.demo.exception.PublicException;
import com.example.demo.util.Result;
import com.example.demo.vo.ExcelUserVo;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/excel")
public class ExcelController {

    // 读取excel
    @PostMapping("/upload")
    public Result<List<ExcelUserVo>> upload(@RequestParam("file") MultipartFile file) {
        if(file.isEmpty()){
            throw new PublicException("请上传文件");
        }
        try {
            ExcelListener<ExcelUserVo> excelListener = new ExcelListener<>();
            FastExcel.read(file.getInputStream(), ExcelUserVo.class, excelListener).sheet().doRead();

            // 读数据
            List<ExcelUserVo> users = excelListener.getExcelListenerList();
            return Result.success(users);
        } catch (IOException e) {
            throw new PublicException("写入异常");
        }

    }

    // 写入excel
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("test-excel", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        try (OutputStream out = response.getOutputStream()) {
            FastExcel.write(out, ExcelUserVo.class)
                    .sheet("模板")
                    .doWrite(getUser());
        } catch (IOException e) {
            throw new IOException(e);
        }
    }

    public List<ExcelUserVo> getUser() {
        ExcelUserVo u1 = new ExcelUserVo(1, "甲");
        ExcelUserVo u2 = new ExcelUserVo(1, "乙");

        return List.of(u1, u2);
    }

}
